package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

/**
 * 登录校验切面类
 */
@Aspect
@Component
public class TsLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object login(ProceedingJoinPoint joinPoint,TsLogin tsLogin) throws Throwable {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("token");
            //判断是否需要登录校验
            if(tsLogin.required()){//需要校验
                if(StringUtils.isEmpty(token)){
                    throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                }else {
                    String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                    if (!redisTemplate.hasKey(loginKey)){
                        throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
                    }

                }
            }
            //如果token不为空，将userInfo放入线程中
            if (!StringUtils.isEmpty(token)){
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(loginKey);
                //如果不为空，则放入线程
                if (userInfo != null){
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }
            return joinPoint.proceed();
        } finally {
            AuthContextHolder.removeUserId();
        }
    }
}
